package cn.ljy.authority.config.security.sms;


import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 自定义的身份验证令牌类，专门用于将手机验证码封装成本类，以便后续用于手机短信验证码登录的身份验证流程。
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal; // 手机号码
    private Object credentials; // 短信验证码

    // 未认证令牌的构造函数
    public SmsCodeAuthenticationToken(Object principal, String credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setAuthenticated(false);//标记为未认证
    }

    // 已认证令牌的构造函数
    public SmsCodeAuthenticationToken(Object principal, String credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = null; // 认证后清除凭证信息
        super.setAuthenticated(true);//标记为已认证
    }

    // 在 SmsCodeAuthenticationToken.java 中添加新的构造函数
//    public SmsCodeAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
//        super(authorities);
//        this.principal = principal;
//        this.credentials = credentials;
//        super.setAuthenticated(true);
//    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {//防止直接设置为已认证状态，确保必须通过认证流程
            throw new IllegalArgumentException(
                    "不能直接设置为可信状态 - 请使用带有权限列表的构造函数");
        }
        super.setAuthenticated(false);
    }

    //清除凭证信息
    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        //认证完成后清除验证码等敏感数据，提高安全性
        this.credentials = null;
    }
}

